package com.k7k7.cserver.client;

import com.k7k7.client.BaseClient;
import com.k7k7.util.ElementUtil;
import com.k7k7.sserver.client.UserCmd;
import com.k7k7.db.UserManager;
import org.apache.log4j.Logger;
import org.dom4j.Element;
import org.dom4j.DocumentHelper;

import java.net.Socket;

/**
 * User: Administrator
 * Date: 2009-4-27
 * Time: 11:47:11
 */
public class ClientC extends BaseClient {
	private Logger log = Logger.getLogger(ClientC.class);

	public ClientC(Socket client) throws Exception {
		super(client);
		ClientMgrC.getInstance().add(this);
	}

	/**
	 * 启动时出现错误
	 */
	@Override
	public void startError() {
		log.fatal("Control Server start error");
	}

	/**
	 * 处理各种消息
	 *
	 * @param root
	 */
	@Override
	public void handleMsg(Element root) {
		String rootName = root.getName();
		if (rootName.equals("pac")) {
			//generate back root tag
			Element _pac = (Element) root.clone();
			ElementUtil.removeAllChild(_pac);
			this.sendPac = _pac;
			//
			Element cmd = (Element) root.elements().get(0);
			String cmdtitle = cmd.attributeValue("cmd").toLowerCase();
			//
			if (cmdtitle.equals(UserCmd.user_register_info)) {
				this.register(cmd.elementText("rname"), cmd.elementText("rpassword"), cmd.elementText("rsex"));
			} else if (cmdtitle.equals(UserCmd.user_login)) {
				this.login(cmd.elementText("fname"), cmd.elementText("fpassword"));
			}
		}
	}

	private void login(String name, String pwd) {
		Element re = DocumentHelper.createElement("pac");
		Element ele = DocumentHelper.createElement("msg");
		if (UserManager.getInstance().login(name, pwd) != null) {
			sendEntryCodeToSceneServer();
			ele.addAttribute("validate", "0");
			//todo:server list
		} else {
			ele.addAttribute("validate", "1");
		}
		re.add(ele);
		this.send(re);
	}

	/**
	 * todo:给游戏服务器发送一个密钥.用于验证正在登录的用户
	 */
	private void sendEntryCodeToSceneServer() {
	}

	/**
	 * <pac id="2">
	 * <msg cmd="register_info">
	 * <rname>{dis_username.text}</rname>
	 * <rpassword>{dis_fpassword.text}</rpassword>
	 * <rsex>{sex}</rsex>
	 * </msg>
	 * </pac>
	 *
	 * @param name
	 * @param password
	 * @param sex
	 */
	private void register(String name, String password, String sex) {
		Element re = DocumentHelper.createElement("pac");
		Element ele = DocumentHelper.createElement("msg");
		if (UserManager.getInstance().newUser(name, password, sex.equals("1")) != null) {
			ele.addAttribute("validate", "0");
		} else {
			ele.addAttribute("validate", "1");
		}
		re.add(ele);
		this.send(re);
	}
}
